# -*- coding:utf-8 -*-
import json
from pathlib import Path

from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout)

from app.common.const_value import TargetLanguage

from app.view.widget.menu_group import MenuGroup

from app.view.widget.protoc_group import ProtocGroup
from app.view.widget.proto_group import ProtoGroup
from app.view.widget.server_group import ServerGroup
from app.view.widget.client_group import ClientGroup
from app.view.widget.btn_group import BtnGroup
from app.view.widget.log_group import LogGroup

class AppView(QMainWindow):
    """
    mvc 框架 view
    """
    def __init__(self):
        super().__init__()
        self.controller = None
        # 基础路径
        self.base_dir = Path(__file__).parent.parent
        self.i18n_dir = self.base_dir / "i18n"
        # 加载语言字典
        self.language_dict = {}
        self.load_languages()
        
        # 设置默认语言
        self.current_lang = "zh_CN"

        self.init_ui()
        self.setWindowTitle("Protoc2xxx proto文件转换格式小工具 （裴文浩 64054443@qq.com)")
        self.resize(800, 600)

        # 设置初始语言
        self.set_language(self.current_lang)

    def init_ui(self):
        """
        初始化UI界面
        """
        # 主界面
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        # 整体布局（垂直）
        main_layout = QVBoxLayout(central_widget)    
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)  
        # 设置菜单
        self.menu_bar = MenuGroup(self.language_dict, self)
        main_layout.addWidget(self.menu_bar) 
        # 1. 读取protoc路径设置
        self.protoc_group = ProtocGroup()
        main_layout.addWidget(self.protoc_group)
        # 2. 读取proto路径设置
        self.proto_group = ProtoGroup()
        main_layout.addWidget(self.proto_group)
        # 3. 导出服务端类型路径设置
        self.server_group = ServerGroup()
        main_layout.addWidget(self.server_group)
        # 4. 导出客户端类型路径设置
        self.client_group = ClientGroup()
        main_layout.addWidget(self.client_group)
        # 5. 操作按钮组
        self.btn_group = BtnGroup()
        main_layout.addWidget(self.btn_group)
        # 6. 日志显示组件
        self.log_group = LogGroup()
        main_layout.addWidget(self.log_group)

    def bind_controller(self, controller):
        """
        给各个组件绑定控制器
        :param controller: 控制器实例
        """
        self.controller = controller
        # 文件目录绑定
        self.protoc_group.protoc_btn_choose.clicked.connect(controller.handle_protoc_directory_selection)
        self.proto_group.proto_btn_choose.clicked.connect(controller.handle_proto_directory_selection)
        # radiobutton 绑定
        self.server_group.server_rbToJava.toggled.connect(lambda:controller.server_radio_button_changed(self.server_group.server_rbToJava))
        self.server_group.server_rbToGolang.toggled.connect(lambda:controller.server_radio_button_changed(self.server_group.server_rbToGolang))
        self.server_group.server_rbToCSharp.toggled.connect(lambda:controller.server_radio_button_changed(self.server_group.server_rbToCSharp))
        self.client_group.client_rbToJava.toggled.connect(lambda:controller.client_radio_button_changed(self.client_group.client_rbToJava))
        self.client_group.client_rbToGolang.toggled.connect(lambda:controller.client_radio_button_changed(self.client_group.client_rbToGolang))
        self.client_group.client_rbToCSharp.toggled.connect(lambda:controller.client_radio_button_changed(self.client_group.client_rbToCSharp))
        # 导目录选择按钮绑定
        self.server_group.server_export_btn_choose.clicked.connect(controller.handle_server_directory_selection)
        self.client_group.client_export_btn_choose.clicked.connect(controller.handle_client_directory_selection)
        # 操作button绑定
        self.btn_group.btn_save.clicked.connect(controller.handle_save)
        self.btn_group.btn_export.clicked.connect(controller.handle_export)
        # 绑定菜单栏信号
        self.menu_bar.bind_about_action(controller.show_about_dialog)
        self.menu_bar.language_changed.connect(self.change_language)

    # 视图更新方法
    def update_protoc_path(self, path):
        self.protoc_group.protoc_path_input.setText(path)

    def update_proto_path(self, path):
        self.proto_group.proto_path_input.setText(path)

    def update_server_path(self, path):
        self.server_group.server_export_path_input.setText(path)

    def update_client_path(self, path):
        self.client_group.client_export_path_input.setText(path)
    
    def update_server_export_type(self, export_type):
        if export_type == TargetLanguage.JAVA.value:
            self.server_group.server_rbToJava.setChecked(True)
        elif export_type == TargetLanguage.GO.value:
            self.server_group.server_rbToGolang.setChecked(True)
        elif export_type == TargetLanguage.CSHARP.value:
            self.server_group.server_rbToCSharp.setChecked(True)
    
    def update_client_export_type(self, export_type):
        if export_type == TargetLanguage.JAVA.value:
            self.client_group.client_rbToJava.setChecked(True)
        elif export_type == TargetLanguage.GO.value:
            self.client_group.client_rbToGolang.setChecked(True)
        elif export_type == TargetLanguage.CSHARP.value:
            self.client_group.client_rbToCSharp.setChecked(True)

    def update_log_view(self, content):
        self.log_group.log_view.setPlainText(content)

    def load_languages(self):
        """从i18n目录加载所有语言文件"""
        self.language_dict = {}
        # 支持的语言列表
        supported_languages = ["zh_CN", "en_US"]
        # 加载语言文件
        for lang in supported_languages:
            file_path = self.i18n_dir / f"{lang}.json"
            try:
                if file_path.exists():
                    with open(file_path, 'r', encoding='utf-8') as f:
                        self.language_dict[lang] = json.load(f)
                else:
                    # 如果文件不存在，创建默认字典
                    self.language_dict[lang] = {
                        "lang_name": lang,
                        "app_title": f"Protoc2xxx ({lang})",
                        "menu_file": "File(&F)",
                        "menu_language": "Language(&L)",
                        "menu_lang_manage": "Language Management",
                        "menu_help": "Help(&H)",
                        "action_about": "About(&A)",
                        "about_text": "Protoc2xxx Converter Tool\nVersion 1.0\nAuthor: Pei Wenhao\nEmail: 64054443@qq.com\n\nThis tool supports multi-language switching functionality",
                        "select_dir": "Select Directory",
                        "export_dir": "Export File Save Directory...",
                        "protoc_title": "Protoc Path Settings",
                        "protoc_path_placeholder": "Directory containing protoc command...",
                        "proto_title": "Proto Path Settings",
                        "proto_path_placeholder": "Directory containing proto files...",
                        "server_title": "Server Export Settings",
                        "client_title": "Client Export Settings",
                        "btn_title": "Quick Actions",
                        "btn_save": "Save Configuration",
                        "btn_export": "Start Conversion",
                        "log_title": "Log Output"
                    }
            except Exception as e:
                print(f"加载语言文件 {file_path} 失败: {str(e)}")
                # 创建简单默认字典
                self.language_dict[lang] = {
                    "lang_name": lang,
                    "app_title": f"Protoc2xxx ({lang})"
                }
                
    def set_language(self, lang_code):
        """
        设置应用程序语言
        :param lang_code: 语言代码 (如 'zh_CN', 'en_US')
        """
        if lang_code not in self.language_dict:
            # 如果请求的语言不存在，使用第一个可用语言
            lang_code = next(iter(self.language_dict.keys()), "zh_CN")
            
        self.current_lang = lang_code
        lang_data = self.language_dict[lang_code]
        
        # 更新窗口标题
        self.setWindowTitle(lang_data.get("app_title", "Protoc2xxx"))
        
        # 更新菜单栏语言
        self.menu_bar.set_language(lang_data)
        self.menu_bar.set_current_language(lang_code)
        # 通知子组件更新语言
        self.protoc_group.set_language(lang_data)
        self.proto_group.set_language(lang_data)
        self.server_group.set_language(lang_data)
        self.client_group.set_language(lang_data)
        self.btn_group.set_language(lang_data)
        self.log_group.set_language(lang_data)

    def change_language(self, lang_code):
        """
        切换应用程序语言
        :param lang_code: 语言代码
        """
        if lang_code == self.current_lang:
            return
            
        self.set_language(lang_code)
        
        # 保存语言设置
        if self.controller:
            self.controller.save_language_setting(lang_code)
